<template>
  <div>
    <SearchFormExtend
      ref="searchForm"
      :search-config="searchConfig"
      :label-width="150"
      @clear="clearSearch"
      @search="handleSearch"
      @visible-change="handleVisibleChange"
    />
    <table-box ref="tableBox" no-request show-index show-selection :other-filters="comFiltersRaw" :other-raw="comParamsRaw" :table-config="tableConfig" @selection-change="handleSelectionChange" @btnOperate="handleBtnOperate" />
    <export-files
      v-if="exportisible"
      title="导出"
      :visible.sync="exportisible"
      download-url=""
      download-prefix=""
      :config="exportConfig"
      :success-fun="(config,res)=>{}"
      @success="handleExportSuccess"
    />

    <import-files
      title="导入"
      :visible.sync="importVisible"
      :config="fileImportConfig"
      :success-fun="(config,res)=>{}"
      @success="handleImportSuccess"
      @close="handleImportClose"
    />
    <import-files
      title="分配导入"
      :visible.sync="allocateImportVisible"
      :config="allocateFileImportConfig"
      :success-fun="(config,res)=>{}"
      @success="handleImportSuccess"
      @close="handleImportClose"
    />
    <import-files
      title="批量变更客户经理导入"
      :visible.sync="changePersonImportVisible"
      :config="changePersonFileImportConfig"
      :success-fun="(config,res)=>{}"
      @success="handleImportSuccess"
      @close="handleImportClose"
    />
    <Disabled ref="disabled" @on-success="()=>refreshTableBoxData('onPage')" />
    <!-- <Distribution ref="allocate" @on-success="()=>refreshTableBoxData('onPage')" /> -->
    <Undistribution ref="unallocate" @on-success="()=>refreshTableBoxData('onPage')" />
    <PersonChange ref="personChange" @on-success="()=>refreshTableBoxData('onPage')" />
  </div>
</template>
<script>
import Disabled from './Disabled'
// import Distribution from './Distribution'
import Undistribution from './Undistribution'
import PersonChange from './PersonChange'
import SearchFormExtend from '@/components/SearchFormExtend'
import { enableTask, downTemplate, downAllocateTemplate, downChangePersonTemplate, distributedTask } from '@/api/channelTask2/storeUpgradeTask'
import { getToken } from '@/utils/auth'
export default {
  name: 'Table',
  components: {
    Disabled,
    // Distribution,
    Undistribution,
    SearchFormExtend,
    PersonChange
  },
  props: {
    tableName: {
      type: String,
      default: 'all'
    },
    tabIndex: {
      type: Number,
      default: 1
    },
    buttonGroupCode: {
      type: String,
      default: 'default'
    }
  },
  data() {
    return {
      searchConfig: [
        { label: '市场编码', prop: 'marketCode', type: 'text', value: '', placeholder: '' },
        { label: '市场名称', prop: 'marketName', type: 'text', value: '', placeholder: '支持模糊查询' },
        {
          type: 'select',
          prop: 'marketType',
          label: '市场类型',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/TOBE_MARKET_TYPE`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'select',
          prop: 'marketNatrue',
          label: '市场属性',
          value: [],
          placeholder: '',
          config: {
            remote: false,
            filterable: true,
            multiple: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/MARKET_NATURE`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'select',
          prop: 'marketFollowUpStage',
          label: '市场跟进进度',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            multiple: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/CTM_MARKET_BUID_PROGRESS`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          label: '客户经理',
          prop: 'responsibleCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          inputListener: (v, getSelections) => {
            const property = /^[\da-zA-Z]+$/.test(v) ? 'adAccount' : 'personName'
            const filtersRaw = [{ id: property, property, value: v, operator: 'like' }]
            getSelections(filtersRaw, {})
          },
          keywordReg: v => /^[\da-zA-Z]+$/.test(v) ? 'adAccount' : 'personName',
          parentListeners: {
            agencyCode: (parentProp, parentValue, getSelections, setValue, { config }) => {
              const filtersRaw = []
              if (parentValue && parentValue.length > 0) {
                filtersRaw.push({ id: 'agencyCode', property: 'agencyCode', value: parentValue[0].code, operator: '=' })
              }
              setValue('')
              getSelections(filtersRaw)
            }
          },
          config: {
            remote: false,
            // paramField: 'keyWord',// 远程搜索参数名
            requestMethod: 'post',
            remoteUrl: `${process.env.VUE_APP_BASE_API}/api/v1/user/personOrg/page`,
            paramField: 'keyWordKey1', // 远程搜索参数名
            defaultProps: {
              label: 'personName',
              value: 'adAccount'
            },
            selectData: []
          },
          dialogConfig: {
            title: '客户经理',
            paramField: 'keyWordKey1', // 远程搜索参数名
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/user/personOrg/page`,
            setting: [{ prop: 'adAccount', title: '编码' }, { prop: 'personName', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '办事处',
          prop: 'agencyCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: '/select-service/api/v1/organization/page',
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '办事处',
            interfacePath: '/select-service/api/v1/organization/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            filtersRaw: [{ 'id': 'isOffice', 'property': 'isOffice', 'value': '1', 'operator': '=' }],
            pageFlag: true
          }
        },
        { label: '门店编码', prop: 'shopCode', type: 'text', value: '', placeholder: '支持批量查询' },
        { label: '门店名称', prop: 'shopName', type: 'text', value: '', placeholder: '支持模糊查询' },
        {
          type: 'select',
          prop: 'isKeyMarket',
          label: '是否重点市场',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/BOOLEANS`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        { label: '市场地址', prop: 'address', type: 'text', value: '', placeholder: '支持模糊查询', operator: 'like' },
        {
          type: 'select',
          prop: 'allocationStatus',
          label: '分配状态',
          value: '',
          placeholder: '',
          disabled: false,
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/CTM_ALLOCATE_STYLE`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'radio',
          prop: 'enable',
          label: '启用状态',
          value: '1',
          placeholder: '',
          config: {
            remote: false,
            defaultProps: {
              label: 'label',
              value: 'value'
            },
            selectData: [
              { label: '全部', value: '' },
              { label: '启用', value: '1' },
              { label: '停用', value: '0' }
            ]
          }
        },
        {
          type: 'select',
          prop: 'isExceptionReporting',
          label: '是否属于异常报备',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/BOOLEANS`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'text',
          prop: 'dataSourceMsg',
          label: '数据来源描述',
          operator: 'like'
        },
        {
          type: 'text',
          prop: 'upgradeRequirement',
          label: '升级改造要求',
          operator: 'like'
        },
        {
          type: 'select',
          prop: 'taskType',
          label: '任务类型',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/CTM_MARKET_TASK_TYPE`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'select',
          prop: 'settlementMethod',
          label: '结案方式',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/CTM_CLOSED_TYPE`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          label: '结案时间',
          prop: 'settlementDate',
          type: 'date',
          value: '',
          placeholder: '请选择结案时间',
          dateConfig: {
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd'
          }
        }

      ],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/page`,
        hideSearchBar: true,
        tabIndex: 1,
        buttonGroupCode: 'default',
        order: 'DESC',
        sort: 'createTime',
        // sortersRow: [
        //   { 'id': 'createTime', 'property': 'createTime', 'direction': 'DESC' },
        //   { 'id': 'taskCode', 'property': 'taskCode', 'direction': 'DESC' }
        // ],
        setting: [
          {
            prop: 'marketCode',
            label: '市场任务编码',
            className: 'btn-green',
            minWidth: 130,
            isButton: true,
            clickFun: this.toDetail
          },
          {
            prop: 'marketName',
            label: '市场名称',
            minWidth: 130
          },
          {
            prop: 'address',
            label: '市场地址',
            minWidth: 130,
            formatData: v => {
              if (v.address) {
                return v.address
              }
              return 'provinceName cityName districtName streetName'.split(' ').map(k => v[k]).filter(e => e !== undefined && e !== null && e !== '').join('/')
            }
          },
          {
            prop: 'marketType',
            label: '市场类型',
            minWidth: 120,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'TOBE_MARKET_TYPE'
            }
          },
          {
            prop: 'marketNatrue',
            label: '市场属性',
            minWidth: 120,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'MARKET_NATURE'
            }
          },
          {
            prop: 'isKeyMarket',
            label: '是否重点市场',
            minWidth: 130,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'agencyName',
            label: '所属办事处',
            minWidth: 130
          },
          {
            prop: 'customerCode',
            label: '客户编码',
            minWidth: 120
          },
          {
            prop: 'shopCode',
            label: '门店编码',
            minWidth: 120
          },
          {
            prop: 'shopName',
            label: '门店名称',
            minWidth: 130
          },
          {
            prop: 'responsibleCode',
            label: '客户经理编码',
            minWidth: 130
          },
          {
            prop: 'responsibleName',
            label: '客户经理名称',
            minWidth: 130
          },
          {
            prop: 'responsibleType',
            label: '客户经理类型',
            minWidth: 130
            // render: (h, row) => {
            //   return h('c-mdm-view', {
            //     props: {
            //       value: row.responsibleType,
            //       label: row.responsibleTypeName,
            //       docCode: 'QY079'
            //     }
            //   })
            // }
          },
          {
            prop: 'responsiblePhone',
            label: '客户经理联系电话',
            minWidth: 130
          },
          {
            prop: 'dataSource',
            label: '数据来源',
            minWidth: 100,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'CTM_MARKET_DATA_FROM'
            }
          },
          {
            prop: 'registerTime',
            label: '登记日期',
            minWidth: 140,
            formatData: this.$trimHMSFormatData('registerTime')
          },
          {
            prop: 'taskType',
            label: '任务类型',
            minWidth: 120,
            propEnum: {
              appCode: 'slm',
              domainCode: 'marketing',
              dictTypeCode: 'CTM_MARKET_TASK_TYPE'
            }
          },
          {
            prop: 'marketFollowUpStage',
            label: '市场跟进进度',
            minWidth: 120,
            propEnum: {
              appCode: 'slm',
              domainCode: 'marketing',
              dictTypeCode: 'CTM_MARKET_BUID_PROGRESS'
            }
          },
          {
            prop: 'settlementDate',
            label: '结案日期',
            minWidth: 140,
            formatData: this.$trimHMSFormatData('settlementDate')
          },
          {
            prop: 'allocationStatus',
            label: '分配状态',
            minWidth: 100,
            propEnum: {
              appCode: 'slm',
              domainCode: 'marketing',
              dictTypeCode: 'CTM_ALLOCATE_STYLE'
            }
          },
          {
            prop: 'earliestDistributionMonth',
            label: '最早分配月份',
            minWidth: 100
          },
          {
            prop: 'allocationNumber',
            label: '分配次数',
            minWidth: 100
          },
          {
            prop: 'isExceptionReporting',
            label: '是否属于异常报备',
            minWidth: 150,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'dataSourceMsg',
            label: '数据来源描述',
            minWidth: 140
          },
          {
            prop: 'upgradeRequirement',
            label: '升级改造要求',
            minWidth: 140
          },
          {
            prop: 'enable',
            label: '启用状态',
            minWidth: 100,
            formatData: v => {
              return [1, '1'].includes(v.enable) ? '启用' : '停用'
            }
          }
        ],
        btnList: process.env.NODE_ENV === 'development' ? [
          // 全部
          { buttonName: '新增', optCode: 'add', outerFlag: true },
          { buttonName: '编辑', optCode: 'edit', outerFlag: true },
          { buttonName: '导出', optCode: 'export', outerFlag: true },
          { buttonName: '导入', optCode: 'import', outerFlag: true },
          { buttonName: '启用', optCode: 'enable', outerFlag: true },
          { buttonName: '停用', optCode: 'disable', outerFlag: true },
          { buttonName: '下载导入模板', optCode: 'download_template', outerFlag: true },
          // 待分配
          { buttonName: '分配', optCode: 'allocate', outerFlag: true },
          { buttonName: '取消分配', optCode: 'unallocate', outerFlag: true },
          { buttonName: '下载分配导入模板', optCode: 'allocate_import_tmp', outerFlag: true },
          { buttonName: '分配导入', optCode: 'allocate_import', outerFlag: true },
          { buttonName: '变更客户经理', optCode: 'change_person', outerFlag: true },
          { buttonName: '下载批量变更客户经理模板', optCode: 'cp_import_tmp', outerFlag: true },
          { buttonName: '批量变更客户经理导入', optCode: 'cp_import', outerFlag: true }

        ] : null
      },
      exportisible: false,
      selectedRows: [],
      filtersRaw: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': '1' }],
      paramsRaw: {},
      // 导入
      importVisible: false,
      allocateImportVisible: false,
      // 批量变更客户经理
      changePersonImportVisible: false
    }
  },
  computed: {
    comFiltersRaw() {
      const t = [...this.filtersRaw]
      if (this.tableName !== 'all') {
        t.push({ id: 'allocationStatus1', property: 'allocationStatus', value: this.tableName === 'allocate' ? 'B' : 'A', operator: '=' })
        t.push({ id: 'enable1', property: 'enable', value: '1', operator: '=' })
        t.push({ id: 'marketFollowUpStage1', property: 'marketFollowUpStage', value: '[C,D]', operator: 'NOT IN' })
      }
      return t
    },
    comParamsRaw() {
      return this.paramsRaw
    },
    exportConfig() {
      return [
        {
          code: 'tmp1',
          name: '市场开发-升级任务管理新增',
          async: false, // 同步导出
          templateCode: 'tmp1', // 模板code
          templateApi: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/downloadImportModel` // 模板导出api
        },
        {
          code: 'tmp0',
          name: '市场开发-升级任务管理修改',
          async: false, // 同步导出
          templateCode: 'tmp0', // 模板code
          templateApi: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/downloadEditImportModel` // 模板导出api
        },
        // {
        //   code: 'tmp2',
        //   name: '市场开发-待开发及整改市场管理分配',
        //   async: false, // 同步导出
        //   templateCode: 'tmp2', // 模板code
        //   templateApi: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/downloadImportAllocModel` // 模板导出api
        // },
        {
          code: 'tmp3',
          name: '市场开发-批量变更客户经理',
          async: false, // 同步导出
          templateCode: 'tmp3', // 模板code
          templateApi: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/downloadImportAllocModel` // 模板导出api
        },
        {
          code: 'code1',
          name: '市场开发-升级任务管理',
          async: false, // 同步导出数据
          templateCode: '', // 模板code
          dataApi: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/export`, // 数据导出api
          headers: { token: getToken() },
          filtersRaw: this.comFiltersRaw, // 符合当前查询条件的所有数据行的导出条件(当前数据查询结果对应的条件)
          paramsRaw: this.comParamsRaw,
          sort: 'createTime', // 排序字段
          order: 'desc', // 排序方式
          selectedRows: this.selectedRows, // 当前所选中的数据行
          queryField: 'id'// 指定行导出时使用的查询字段名称
        },
        {
          code: 'code2',
          name: '市场开发-批量变更客户经理导出',
          async: false, // 同步导出数据
          templateCode: '', // 模板code
          dataApi: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/exportAlloc`, // 数据导出api
          headers: { token: getToken() },
          filtersRaw: this.comFiltersRaw, // 符合当前查询条件的所有数据行的导出条件(当前数据查询结果对应的条件)
          paramsRaw: this.comParamsRaw,
          sort: 'createTime', // 排序字段
          order: 'desc', // 排序方式
          selectedRows: this.selectedRows, // 当前所选中的数据行
          queryField: 'id'// 指定行导出时使用的查询字段名称
        }
      ]
    },
    fileImportConfig() {
      return [
        {
          code: 'ctmMarketTaskImportExcelDTO',
          name: '市场开发-升级任务管理新增',
          async: false,
          headers: { token: getToken() },
          apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/importExcel`
        },
        {
          code: 'ctmMarketTaskEditImportExcelDTO',
          name: '市场开发-升级任务管理修改',
          async: false,
          headers: { token: getToken() },
          apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/editImportExcel`
        },
        // {
        //   code: '2',
        //   name: '市场开发-升级任务管理分配导入',
        //   async: false,
        //   headers: { token: getToken() },
        //   apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/importAllocExcel`
        // },
        {
          code: '3',
          name: '市场开发-批量变更客户经理',
          async: false,
          headers: { token: getToken() },
          apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/importAllocExcel`
        }
      ]
    },
    allocateFileImportConfig() {
      return [
        {
          code: '2',
          name: '市场开发-升级任务管理分配',
          async: false,
          headers: { token: getToken() },
          apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/importAllocExcel`
        }
      ]
    },
    changePersonFileImportConfig() {
      return [
        {
          code: '3',
          name: '市场开发-批量变更客户经理',
          async: false,
          headers: { token: getToken() },
          apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarketTask/importAllocExcel`
        }
      ]
    }
  },
  created() {
    this.$set(this.tableConfig, 'tabIndex', this.tabIndex)
    this.$set(this.tableConfig, 'buttonGroupCode', this.buttonGroupCode)
    if (this.tableName !== 'all') {
      const i = this.searchConfig.findIndex(e => e.prop === 'allocationStatus')
      if (i >= 0) {
        this.searchConfig.splice(i, 1)
      }
    }
  },
  mounted() {
    this.refreshTableBoxData()
  },
  methods: {
    clearSearch() {
      this.filtersRaw = [
        { id: 'enable', property: 'enable', value: '1', operator: '=' }
      ]
      this.paramsRaw = {}
      this.$nextTick(() => {
        // 默认启用
        this.$refs.searchForm.updateValue('enable', '1')
      })
    },
    handleSearch({ filtersRaw, paramsRaw }) {
      this.filtersRaw = this.$batchFiltersRawHandle(filtersRaw, 'shopCode')
      this.paramsRaw = paramsRaw
      this.refreshTableBoxData()
    },
    handleVisibleChange() {
      this.refreshTableHeight()
    },
    refreshTableBoxData(flag) {
      this.$nextTick(() => {
        this.$refs.tableBox && this.$refs.tableBox.initTableData(flag)
      })
    },
    refreshTableHeight() {
      this.$nextTick(() => {
        this.$refs.tableBox && this.$refs.tableBox.refreshTableHeight()
      })
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    handleBtnOperate(flag) {
      this[flag] && this[flag]()
    },
    add() {
      this.$pageStack.push('src/views/channelTask2/storeUpgrade/task/components/addEdit.vue', {
        props: {}
      }, (flag) => {
        flag && this.refreshTableBoxData(flag)
      })
    },
    edit() {
      if (!this.singleJudge(this.selectedRows, '编辑', true)) {
        return
      }
      // 40742   【待开发及整改市场管理】编辑功能控制调整
      // 调整前：分配状态为“已分配”的不允许编辑；
      // 调整后：任何分配状态的数据均可以编辑，但是市场跟进进度值为“已完成/已终止”的不能编辑；
      // if (this.selectedRows[0].allocationStatus === 'B') {
      //   this.$message.warning('数据已分配，不允许编辑!')
      //   return
      // }
      if (['C', 'D'].includes(this.selectedRows[0].marketFollowUpStage)) {
        this.$message.warning(`市场跟进进度值为【已完成/已终止】的不允许编辑！`)
        return
      }
      this.$pageStack.push('src/views/channelTask2/storeUpgrade/task/components/addEdit.vue', {
        props: {
          id: this.selectedRows[0].id
        }
      }, (flag) => {
        flag && this.refreshTableBoxData(flag)
      })
    },
    toDetail(row) {
      this.$pageStack.push('src/views/channelTask2/storeUpgrade/task/components/detail.vue', {
        props: {
          id: row.id
        }
      })
    },
    download_template() {
      downTemplate('待开发及整改市场管理导入模板.xlsx').then(() => {
        this.$message.success('模板下载成功!')
      })
    },
    allocate_import_tmp() {
      downAllocateTemplate('待开发及整改市场管理分配导入模板.xlsx').then(() => {
        this.$message.success('模板下载成功!')
      })
    },
    export() {
      this.exportisible = true
    },
    import() {
      this.importVisible = true
    },
    allocate_import() {
      this.allocateImportVisible = true
    },
    change_person() {
      if (!this.singleJudge(this.selectedRows, '变更客户经理', true)) {
        return
      }
      if (this.selectedRows[0].allocationStatus === 'A') {
        this.$message.warning('只能变更已分配项!')
        return
      }
      this.$refs.personChange.openDialog(this.selectedRows[0])
    },
    cp_import_tmp() {
      downChangePersonTemplate('批量变更客户经理导入模板.xlsx').then(() => {
        this.$message.success('模板下载成功!')
      })
    },
    cp_import() {
      this.changePersonImportVisible = true
    },
    enable() {
      if (!this.singleJudge(this.selectedRows, '启用')) {
        return
      }
      // 可批量操作，只能启用停用状态的数据；
      if (this.selectedRows.some(e => [1, '1'].includes(e.enable))) {
        this.$message.warning('所选项包含启用数据!')
        return
      }
      this.$msgbox({
        title: '启用',
        showCancelButton: true,
        message: `<div>将启用<span style="color:red;">${this.selectedRows.length}</span>条数据?</div>`,
        dangerouslyUseHTMLString: true
      }).then(() => {
        return enableTask(this.selectedRows.map(e => e.id)).then(res => {
          this.$message.success('操作成功!')
          this.refreshTableBoxData('onPage')
        })
      })
    },
    disable() {
      if (!this.singleJudge(this.selectedRows, '停用', true)) {
        return
      }
      const d = this.selectedRows[0]
      // 分配状态为已分配的数据不允许停用，是否完结值为是的数据不允许停用
      if ([0, '0'].includes(d.enable)) {
        this.$message.warning('所选项状态为【停用】!')
        return
      }
      if (this.selectedRows.some(e => e.allocationStatus === 'B')) {
        this.$message.warning('【已分配】数据不允许停用!')
        return
      }
      if (['C', 'D'].includes(d.marketFollowUpStage)) {
        this.$message.warning('【已完成】或【已终止】数据不允许停用!')
        return
      }
      this.$refs.disabled.openDialog(d)
    },
    async allocate() {
      if (!this.singleJudge(this.selectedRows, '分配')) {
        return
      }
      if (this.selectedRows.some(e => e.allocationStatus === 'B')) {
        this.$message.warning('所选项包含【已分配】项数据!')
        return
      }
      if (this.selectedRows.some(e => ![1, '1'].includes(e.enable))) {
        this.$message.warning('所选项包含【已停用】项数据!')
        return
      }
      if (this.selectedRows.some(e => e.marketFollowUpStage !== 'A')) {
        this.$message.warning('只能操作【市场跟进进度】为【未开始】数据!')
        return
      }
      // 市场XXXX,XXXX（显示市场名称）任务类型/客户经理不能为空，请检查
      let tmp = this.selectedRows.filter(e => e.marketType === undefined || e.marketType === '' || e.marketType === null)
      if (tmp.length > 0) {
        this.$message.warning(`市场【${tmp.map(e => e.marketName).join(',')}】市场任务类型不能为空，请检查!`)
        return
      }
      tmp = this.selectedRows.filter(e => e.responsibleCode === undefined || e.responsibleCode === '' || e.responsibleCode === null)
      if (tmp.length > 0) {
        this.$message.warning(`市场【${tmp.map(e => e.marketName).join(',')}】市场客户经理不能为空，请检查!`)
        return
      }
      // 即将对所选数据进行分配操作，是否确认？
      await this.$msgbox({
        title: '分配',
        message: '即将对所选数据进行分配操作，是否确认？',
        showCancelButton: true
      })
      // this.$refs.allocate.openDialog(this.selectedRows)
      const data = this.selectedRows.map(e => {
        return {
          marketId: e.id,
          responsibleCode: e.responsibleCode,
          responsibleName: e.responsibleName,
          responsiblePhone: e.responsiblePhone
        }
      })
      return distributedTask(data).then(res => {
        this.$message.success('分配成功!')
        this.refreshTableBoxData('onPage')
      })
    },
    unallocate() {
      if (!this.singleJudge(this.selectedRows, '取消分配')) {
        return
      }
      if (this.selectedRows.some(e => e.allocationStatus === 'A')) {
        this.$message.warning('所选项包含【未分配】项数据!')
        return
      }
      this.$refs.unallocate.openDialog(this.selectedRows)
      // this.$msgbox({
      //   title: '取消分配',
      //   message: `取消分配后，所选<span style="color:red;">${this.selectedRows.length}</span>条数据将取消作为客户经理当月任务，是否确认?`,
      //   dangerouslyUseHTMLString: true,
      //   showCancelButton: true
      // }).then(() => {
      //   return undistributedTask(this.selectedRows.map(e => e.id))
      // }).then(res => {
      //   this.refreshTableBoxData('onPage')
      //   this.$message.success('操作成功!')
      // })
    },
    handleExportSuccess() {

    },
    handleImportSuccess() {
      this.refreshTableBoxData()
      // console.log('导入成功')
    },
    handleImportClose() {
      // console.log('导入窗口关闭')
    }
  }
}
</script>
